package com.cyh.forum.services.impl;

import com.cyh.forum.common.AppResult;
import com.cyh.forum.common.ResultCode;
import com.cyh.forum.dao.UserMapper;
import com.cyh.forum.exception.ApplicationException;
import com.cyh.forum.model.User;
import com.cyh.forum.services.IUserService;
import com.cyh.forum.utils.MD5Util;
import com.cyh.forum.utils.StringUtil;
import com.cyh.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;


@Slf4j
@Service

public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {


        //  非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword())
        ){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //  查询当前用户是否存在
        User existUser = userMapper.selectByUserName(user.getUsername());
        if (existUser != null){
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "Username = " + user.getUsername());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //  给新增用户填充默认值
        user.setGender((byte) 0);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //  写入数据库
        int row = userMapper.insertSelective(user);
        //  如果插入失败
        if (row != 1){
            //  打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //  插入成功,打印日志
        log.info(ResultCode.SUCCESS.toString());

    }



    @Override
    public User selectByUserName(String username) {
        //  非空校验
        if (StringUtil.isEmpty(username)){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //  对用户名非空校验
        if (StringUtil.isEmpty(username)){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //  根据用户名查询用户信息
        User user = selectByUserName(username);

        //  对查询结果进行非空校验
        if (user == null){
            //  打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //  判断密码是否一致
            //  对用户输入的密码加密成密文
        String encryptedPassword = MD5Util.md5Salt(password,user.getSalt());
            //  比较与数据库中的密文 是否一致
        if (!encryptedPassword.equals(user.getPassword())){
                //  打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", 密码错误 , username = " + username);
                //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //  打印登录成功的日志
        log.info("username为 " + username + "  的用户,登录成功");
        //  没有抛出异常,则说明验证通过,返回user对象
        return user;
    }

    @Override
    public User selectById(Long id) {
        //  非空校验
        if (id == null){
            //  打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));
        }
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //  参数校验
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  调用 DAO 层, 根据id从数据库中获取数据
        User user = userMapper.selectByPrimaryKey(id);
        //  校验用户是否存在
        if (user == null){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + id);
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser = new User();
        //  设置用户 id 和 帖子数量
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        //  此时传入的对象只有Id和ArticleCount不为空,因此只会更新这两个数值
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //  校验row是否正常
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不为 1 ");
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //  非空校验
        if (id == null || id <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  校验用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + "userID = " + id);
            //  抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //  设置删除对象
        User delete = new User();
        delete.setId(id);
        delete.setArticleCount(user.getArticleCount() - 1);
        //  判断减一后 帖子数量是否小于0
        if (delete.getArticleCount() < 0){
            //  如果小于0 则设置为零
            delete.setArticleCount(0);
        }
        //  调用DAO层
        val row = userMapper.updateByPrimaryKeySelective(delete);
        //  校验删除是否成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED_ARTICLE_DELETE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_DELETE));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //  非空校验
        if(user == null || user.getId() == null || user.getId() <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //  校验用户是否存在
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if (existUser == null || existUser.getDeleteState() != 0){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //  设置更新标识符
        boolean checkUpdate = false;
        //  设置更新对象
        User update = new User();
        update.setId(user.getId());

        //  校验用户名是否已存在
        if ( !StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(existUser.getUsername()) ){
            //  校验更改后的用户名是否是唯一的
            User userNameNull = userMapper.selectByUserName(user.getUsername());
            if (userNameNull != null){
                //  打印日志
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                //  抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //  设置用户名
            update.setUsername(user.getUsername());
            //  更新标识符
            checkUpdate = true;
        }

        //  校验昵称
        if ( !StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(existUser.getNickname()) ){
            //  设置昵称
            update.setNickname(user.getNickname());
            //  更新标识符
            checkUpdate = true;
        }

        //  校验性别
        if (user.getGender() != null && user.getGender() != existUser.getGender()){
            //  不是男也不是女,就保密
            if (user.getGender() != 0 && user.getGender() != 1){
                user.setGender((byte) 2);
            }
            //  设置昵称
            update.setGender(user.getGender());
            //  更新标识符
            checkUpdate = true;
        }

        //  校验邮箱
        if ( !StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(existUser.getEmail()) ){
            //  设置昵称
            update.setEmail(user.getEmail());
            //  更新标识符
            checkUpdate = true;
        }

        //  校验电话
        if ( !StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existUser.getPhoneNum()) ){
            //  设置昵称
            update.setPhoneNum(user.getPhoneNum());
            //  更新标识符
            checkUpdate = true;
        }

        //  校验个人简介
        if ( !StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(existUser.getRemark()) ){
            //  设置昵称
            update.setRemark(user.getRemark());
            //  更新标识符
            checkUpdate = true;
        }

        //  校验更新标识符
        if (checkUpdate == false){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //  更新标识符为true,执行更新操作,调用DAO层
        val row = userMapper.updateByPrimaryKeySelective(update);

        //  校验更新是否成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED.toString() + "受影响的行数不为1");
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //  非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) ||StringUtil.isEmpty(oldPassword)){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  校验用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() != 0){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //  校验老密码是否正确
        String checkOldPassword = MD5Util.md5Salt(oldPassword,user.getSalt());
        if (!checkOldPassword.equals(user.getPassword())){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //  生成一个新的盐值 salt
        String salt = UUIDUtil.UUID_32();
        //  生成一个新的加密密码
        String password = MD5Util.md5Salt(newPassword,salt);

        //  构造更新对象
        User update = new User();
        update.setId(id);
        update.setSalt(salt);
        update.setPassword(password);

        //  调用DAO层
        val row = userMapper.updateByPrimaryKeySelective(update);
        //  校验更新是否成功
        if (row != 1){
            //  打印日志
            log.warn(ResultCode.FAILED.toString() + "受影响的行数不为1");
            //  抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }


}
